<template>
  <div class="register-page">
    <div class="register-title">
      <div class="register-title-child1th">创建您的<span class="span">账号</span></div>
    </div>
    <div class="register-from">
      <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
        <el-form-item prop="username">
          <el-input v-model="form.username" maxlength="12" type="text" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" maxlength="15" type="password" placeholder="密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password_repeat">
          <el-input v-model="form.password_repeat" maxlength="15" type="password" placeholder="确认密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="form.email" type="text" placeholder="电子邮箱地址">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="register-email" prop="code">
          <el-row :gutter="10">
            <el-col :span="17">
              <el-input v-model="form.code" maxlength="6" type="text" placeholder="请输入验证码">
                <template #prefix>
                  <el-icon><EditPen /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="5">
              <el-button class="register-email-button" @click="validateEmail" :disabled="!isEmailValid || refreshTime > 0">
                {{refreshTime > 0 ? '剩余' + refreshTime + '秒' : '获取验证码'}}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <div class="register-register">
      <el-button class="register-register-button" @click="register" type="warning" plain>立即注册</el-button>
    </div>
    <div class="register-login">
      已有账号？<el-link class="register-login-link" type="primary" @click="router.push('/')">立即登录</el-link>
    </div>
  </div>
</template>

<script setup>

import {EditPen, Lock, Message, User} from "@element-plus/icons-vue";
import router from "@/router/index.js";
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {post} from "@/api/request.js";

const form = reactive({
  username: '',
  password: '',
  password_repeat: '',
  email: '',
  code: ''
})
// 用户名校验规则
const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else if (!/^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(value)) {
    callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
  } else {
    callback()
  }
}
// 重复密码校验规则
const validatePasswordRepeat = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}
const rules = {
  username: [
    { validator: validateUsername, trigger: ['blur', 'change'] }, // 修改或失去焦点时触发
    { min: 2, max: 12, message: '用户名的长度必须在2-12个字符之间', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
    { min: 6, max: 15, message: '密码的长度必须在6-15个字符之间', trigger: ['blur', 'change'] }
  ],
  password_repeat: [
    { validator: validatePasswordRepeat, trigger: ['blur', 'change'] }
  ],
  email: [
    { required: true, message: '请输入邮件地址', trigger: ['blur', 'change'] },
    { type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change'] }
  ],
  code: [
    { min: 6, max: 6, required: true, message: '请输入验证码', trigger: ['blur', 'change'] }
  ]
}
const formRef = ref()
const isEmailValid = ref(false)
const refreshTime = ref(0)
const onValidate = (prop, isValid) => {
  if (prop === 'email')
    isEmailValid.value = isValid
}

const register = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/register', {
        username: form.username,
        password: form.password,
        email: form.email,
        code: form.code
      }, (message) => {
        ElMessage.success(message)
        router.push("/")
      })
    } else {
      ElMessage.warning("请填写完整信息")
    }
  })
}

const validateEmail = () => {
  refreshTime.value = 60
  post('api/auth/valid-register-email', {
    email: form.email
  }, (message) => {
    ElMessage.success(message)
    setInterval(() => refreshTime.value--, 1000) // 每秒减1
  }, (message) => {
    refreshTime.value = 0
    ElMessage.warning(message)
  })
}
</script>

<style scoped>
  @import "@/assets/css/welcome/register-page.scss";
</style>